package com.sduept.i1.model;

import java.util.HashMap;
import java.util.Map;

// 图像存储管理
public class ImageStorageManagement {
	private Map<String, ImageStorage> map;

	public ImageStorageManagement() {
		this.map = new HashMap<String, ImageStorage>();
	}

	// 创建图像存储
	public void createImageStorage(String deviceId, int channelNo, int imageId, int packetNo) {
		if (!this.map.containsKey(deviceId + channelNo)) {
			this.map.put(deviceId + channelNo, new ImageStorage(imageId, packetNo));
		}
	}

	// 存储图像数据
	public void storePacket(String deviceId, int channelNo, int subpacketNo, byte[] data) {
		ImageStorage s = map.get(deviceId + channelNo);
		if (s != null) {
			s.storePacket(subpacketNo, data);
		}
	}

	// 获取未接收的子包编号
	public int[] getLostSubpacketNos(String deviceId, int channelNo) {
		ImageStorage s = map.get(deviceId + channelNo);
		if (s != null) {
			return s.getLostSubpacketNos();
		}
		return new int[] {};
	}
	
	// 获取图像id
	public int getImageId(String deviceId, int channelNo) {
		ImageStorage s = map.get(deviceId + channelNo);
		if (s != null) {
			return s.getImageId();
		}
		return -1;
	}

	public class ImageStorage {
		private int imageId; // 图像id
		private int packetNo; // 总包数
		private byte[][] imageData; // 图像数据
		private int received; // 当前已经收到的包数

		private ImageStorage(int imageId, int packetNo) {
			this.imageId = imageId;
			this.packetNo = packetNo;
			this.imageData = new byte[packetNo][];
			this.received = 0;
		}

		private void storePacket(int subpacketNo, byte[] data) {
			this.imageData[subpacketNo] = data;
			this.received++;
		}

		private int[] getLostSubpacketNos() {
			int[] lostSubpacketNos = new int[packetNo - received];
			int currentNo = 0;

			for (int i = 0; i < packetNo; i++) {
				if (imageData[i] == null) {
					lostSubpacketNos[currentNo++] = i;
				}
			}

			return lostSubpacketNos;
		}
		
		private int getImageId() {
			return this.imageId;
		}
	}

}
